package fairygui.editor
{
   import com.greensock.plugins.BezierPlugin;
   import com.greensock.plugins.BezierThroughPlugin;
   import com.greensock.plugins.HexColorsPlugin;
   import com.greensock.plugins.TweenPlugin;
   import fairygui.UIConfig;
   import fairygui.UIObjectFactory;
   import fairygui.UIPackage;
   import fairygui.editor.dialogs.ControllerActionItem;
   import fairygui.editor.dialogs.ControllerPageItem;
   import fairygui.editor.extui.ChildObjectInput;
   import fairygui.editor.extui.ColorInput;
   import fairygui.editor.extui.EditableTreeItem;
   import fairygui.editor.extui.LinkButton;
   import fairygui.editor.extui.ListItemInput;
   import fairygui.editor.extui.ListItemResourceInput;
   import fairygui.editor.extui.NumericInput;
   import fairygui.editor.extui.ResourceInput;
   import fairygui.editor.extui.TextInput;
   import fairygui.editor.gui.EUIProject;
   import fairygui.editor.handlers.NativeInvokeHandler;
   import fairygui.editor.loader.Downloader;
   import fairygui.editor.props.GearPropsItem;
   import fairygui.editor.settings.Preferences;
   import fairygui.editor.utils.UtilsFile;
   import fairygui.editor.utils.UtilsStr;
   import fairygui.utils.ZipReader;
   import flash.desktop.NativeApplication;
   import flash.desktop.NativeProcess;
   import flash.desktop.NativeProcessStartupInfo;
   import flash.display.NativeWindow;
   import flash.display.NativeWindowInitOptions;
   import flash.display.Sprite;
   import flash.display.StageAlign;
   import flash.display.StageScaleMode;
   import flash.events.Event;
   import flash.events.IOErrorEvent;
   import flash.events.InvokeEvent;
   import flash.filesystem.File;
   import flash.system.Capabilities;
   import flash.utils.ByteArray;
   
   public class FairyGUIEditor extends Sprite
   {
      
      public static var defaultWindowTitle:String;
      
      public static var language:String;
      
      public static var os_mac:Boolean;
      
      public static var newVersionData:Object;
      
      public static var newVersionPrompt:Boolean;
      
      private static var _newVersionDownloader:Downloader;

       [Embed(source="/assets/basic.zip", mimeType="application/octet-stream")]
      private static var BASIC_PKG:Class;
       [Embed(source="/assets/builder.zip", mimeType="application/octet-stream")]
      private static var BUILDER_PKG:Class;
       
      
      public function FairyGUIEditor()
      {
         var _loc4_:XML = null;
         var _loc5_:String = null;
         var _loc6_:String = null;
         super();
         stage.frameRate = 24;
         stage.align = StageAlign.TOP_LEFT;
         stage.scaleMode = StageScaleMode.NO_SCALE;
         stage.color = 3684408;
         os_mac = Capabilities.os.toLowerCase().indexOf("mac") != -1;
         defaultWindowTitle = stage.nativeWindow.title;
         TweenPlugin.activate([BezierPlugin,BezierThroughPlugin,HexColorsPlugin]);
         XML.ignoreWhitespace = true;
         Preferences.load();
         language = Preferences.language;
         if(language == "auto")
         {
            language = Capabilities.language;
         }
         if(!new File("app:/locales/" + language + "/strings1.xml").exists)
         {
            language = "en";
         }
         var _loc1_:XML = new XML(UtilsFile.loadString(new File("app:/locales/" + language + "/strings1.xml")));
         UIPackage.setStringsSource(_loc1_);
         Consts.g = {};
         var _loc2_:XML = new XML(UtilsFile.loadString(new File("app:/locales/" + language + "/strings2.xml")));
         var _loc3_:XMLList = _loc2_.string;
         for each(_loc4_ in _loc3_)
         {
            _loc5_ = _loc4_.@name;
            _loc6_ = _loc4_.toString();
            Consts.g[_loc5_] = _loc6_;
         }
         Consts.supportedPlatforms = [EUIProject.TYPE_FLASH,EUIProject.TYPE_UNITY,EUIProject.TYPE_STARLING,EUIProject.TYPE_EGRET,EUIProject.TYPE_LAYABOX,EUIProject.TYPE_HAXE];
         UIPackage.addPackage(new BASIC_PKG(),null).loadAllImages();
         UIPackage.addPackage(new BUILDER_PKG(),null).loadAllImages();
         UIPackage.waitToLoadCompleted(this.continueInit);
      }
      
      public static function createOpenProjectWindow(param1:EditorWindow, param2:Boolean) : void
      {
         var _loc3_:NativeWindowInitOptions = new NativeWindowInitOptions();
         _loc3_.resizable = false;
         _loc3_.maximizable = false;
         _loc3_.minimizable = true;
         if(param1 != null)
         {
            _loc3_.owner = param1.stage.nativeWindow;
         }
         var _loc4_:NativeWindow = new NativeWindow(_loc3_);
         _loc4_.width = 545;
         _loc4_.height = 445;
         _loc4_.x = Math.max(0,(Capabilities.screenResolutionX - _loc4_.width) / 2);
         _loc4_.y = Math.max(0,(Capabilities.screenResolutionY - _loc4_.height) / 2);
         _loc4_.title = defaultWindowTitle;
         _loc4_.addEventListener(Event.CLOSE,__winClosed);
         var _loc5_:OpenProjectWindow = new OpenProjectWindow();
         _loc4_.stage.addChild(_loc5_);
         _loc5_.init(param1,param2);
         _loc4_.activate();
      }
      
      public static function createEditorWindow(param1:File, param2:Boolean = false) : EditorWindow
      {
         var _loc3_:NativeWindow = null;
         var _loc6_:String = null;
         var _loc7_:Array = null;
         var _loc8_:int = 0;
         var _loc9_:Sprite = null;
         param1.canonicalize();
         if(!param2)
         {
            _loc6_ = param1.parent.nativePath;
            _loc7_ = NativeApplication.nativeApplication.openedWindows;
            _loc8_ = 0;
            while(_loc8_ < _loc7_.length)
            {
               _loc3_ = _loc7_[_loc8_];
               if(_loc3_.stage.numChildren != 0)
               {
                  _loc9_ = _loc3_.stage.getChildAt(0) as Sprite;
                  if(_loc9_ != null)
                  {
                     if(_loc9_ is EditorWindow && EditorWindow(_loc9_).project.basePath == _loc6_ && _loc3_.visible)
                     {
                        _loc3_.activate();
                        return EditorWindow(_loc9_);
                     }
                  }
               }
               _loc8_++;
            }
         }
         var _loc4_:NativeWindowInitOptions = new NativeWindowInitOptions();
         _loc4_.resizable = true;
         _loc4_.maximizable = true;
         _loc4_.minimizable = true;
         _loc3_ = new NativeWindow(_loc4_);
         _loc3_.width = 1000;
         _loc3_.height = 600;
         _loc3_.x = Math.max(0,(Capabilities.screenResolutionX - _loc3_.width) / 2);
         _loc3_.y = Math.max(0,(Capabilities.screenResolutionY - _loc3_.height) / 2);
         _loc3_.title = defaultWindowTitle;
         _loc3_.addEventListener(Event.CLOSE,__winClosed);
         var _loc5_:EditorWindow = new EditorWindow();
         _loc3_.stage.addChild(_loc5_);
         _loc5_.onlyForPublish = param2;
         _loc5_.init(param1);
         if(!param2)
         {
            _loc3_.activate();
         }
         return _loc5_;
      }
      
      public static function findEditorWindow() : EditorWindow
      {
         var _loc3_:NativeWindow = null;
         var _loc4_:Sprite = null;
         var _loc1_:Array = NativeApplication.nativeApplication.openedWindows;
         var _loc2_:int = 0;
         while(_loc2_ < _loc1_.length)
         {
            _loc3_ = _loc1_[_loc2_];
            _loc4_ = Sprite(_loc3_.stage.getChildAt(0));
            if(_loc4_ is EditorWindow)
            {
               return EditorWindow(_loc4_);
            }
            _loc2_++;
         }
         return null;
      }
      
      public static function findOpenProjectWindow() : OpenProjectWindow
      {
         var _loc3_:NativeWindow = null;
         var _loc4_:Sprite = null;
         var _loc1_:Array = NativeApplication.nativeApplication.openedWindows;
         var _loc2_:int = 0;
         while(_loc2_ < _loc1_.length)
         {
            _loc3_ = _loc1_[_loc2_];
            _loc4_ = Sprite(_loc3_.stage.getChildAt(0));
            if(_loc4_ is OpenProjectWindow && OpenProjectWindow(_loc4_).owner == null)
            {
               return OpenProjectWindow(_loc4_);
            }
            _loc2_++;
         }
         return null;
      }
      
      public static function saveAllAndExit() : void
      {
         var _loc4_:File = null;
         var _loc7_:NativeWindow = null;
         var _loc8_:Sprite = null;
         var _loc1_:Array = NativeApplication.nativeApplication.openedWindows;
         var _loc2_:int = 0;
         while(_loc2_ < _loc1_.length)
         {
            _loc7_ = _loc1_[_loc2_];
            _loc8_ = Sprite(_loc7_.stage.getChildAt(0));
            if(_loc8_ is EditorWindow)
            {
               EditorWindow(_loc8_).close();
            }
            _loc2_++;
         }
         var _loc3_:File = new File(new File(File.applicationDirectory.url).nativePath);
         if(os_mac)
         {
            _loc4_ = _loc3_.resolvePath("../MacOS/FairyGUI-Editor");
         }
         else
         {
            _loc4_ = _loc3_.resolvePath("FairyGUI-Editor.exe");
         }
         var _loc5_:NativeProcessStartupInfo = new NativeProcessStartupInfo();
         _loc5_.executable = _loc4_;
         var _loc6_:NativeProcess = new NativeProcess();
         _loc6_.start(_loc5_);
         NativeApplication.nativeApplication.exit();
      }
      
      public static function onVersionCheckComplete(param1:Object) : void
      {
         if(param1 == null)
         {
            if(VersionCheck.inst.initiator)
            {
               VersionCheck.inst.initiator.mainPanel.showAlreadyUpdatedPrompt();
            }
            return;
         }
         if(!VersionCheck.inst.initiator && Preferences.checkNewVersion == "disabled")
         {
            return;
         }
         newVersionData = param1;
         var _loc2_:File = new File(new File(File.applicationStorageDirectory.url).nativePath).resolvePath("upgrade");
         if(!_loc2_.exists)
         {
            _loc2_.createDirectory();
         }
         var _loc3_:File = _loc2_.resolvePath(UtilsStr.getFileFullName(newVersionData.url));
         if(_loc3_.exists && _loc3_.size == newVersionData.size)
         {
            upgradeFileReady(_loc3_.nativePath);
            return;
         }
         if(_newVersionDownloader && _newVersionDownloader.running)
         {
            return;
         }
         _newVersionDownloader = new Downloader();
         _newVersionDownloader.addEventListener(Event.COMPLETE,onDownloadComplete);
         _newVersionDownloader.addEventListener(IOErrorEvent.IO_ERROR,onDownloadError);
         _newVersionDownloader.download(newVersionData.url,_loc3_.nativePath,3,false);
      }
      
      public static function installUpdate(param1:EditorWindow) : void
      {
         var zipFile:File = null;
         var ba:ByteArray = null;
         var zip:ZipReader = null;
         var appFolder:File = null;
         var entry:Object = null;
         var file:File = null;
         var folder:File = null;
         var initiator:EditorWindow = param1;
         try
         {
            zipFile = new File(newVersionData.filePath);
            ba = UtilsFile.loadBytes(zipFile);
            zip = new ZipReader(ba);
            appFolder = new File(new File(File.applicationDirectory.url).nativePath);
            for each(entry in zip.entries)
            {
               file = appFolder.resolvePath(entry.name);
               folder = file.parent;
               if(!folder.exists)
               {
                  folder.createDirectory();
               }
               UtilsFile.saveBytes(file,zip.getEntryData(entry.name));
            }
            UtilsFile.deleteFile(zipFile);
            if(initiator)
            {
               initiator.mainPanel.showRestartPrompt();
            }
            return;
         }
         catch(err:Error)
         {
            return;
         }
      }
      
      private static function onDownloadComplete(param1:String) : void
      {
         var _loc2_:File = new File(_newVersionDownloader.filePath);
         if(_loc2_.size != newVersionData.size)
         {
            return;
         }
         upgradeFileReady(_newVersionDownloader.filePath);
      }
      
      private static function upgradeFileReady(param1:String) : void
      {
         newVersionData.filePath = param1;
         if(Preferences.checkNewVersion == "auto")
         {
            installUpdate(null);
            return;
         }
         newVersionPrompt = true;
         var _loc2_:EditorWindow = findEditorWindow();
         if(_loc2_)
         {
            _loc2_.showNewVersionPrompt();
         }
      }
      
      private static function onDownloadError(param1:IOErrorEvent) : void
      {
      }
      
      private static function __winClosed(param1:Event) : void
      {
         if(NativeApplication.nativeApplication.openedWindows.length == 1)
         {
            NativeApplication.nativeApplication.exit();
         }
      }
      
      private function continueInit() : void
      {
         UIConfig.defaultFont = "Tahoma,_sans";
         UIConfig.defaultScrollBounceEffect = false;
         UIConfig.defaultScrollTouchEffect = false;
         UIConfig.modalLayerAlpha = 0;
         UIConfig.verticalScrollBar = "ui://Basic/ScrollBar_VT";
         UIConfig.horizontalScrollBar = "ui://Basic/ScrollBar_HZ";
         UIConfig.popupMenu = "ui://Basic/PopupMenu";
         UIConfig.popupMenu_seperator = "ui://Basic/MenuSeperator";
         UIConfig.tooltipsWin = "ui://Basic/TooltipsWin";
         UIConfig.defaultComboBoxVisibleItemCount = int.MAX_VALUE;
         UIObjectFactory.setPackageItemExtension("ui://Basic/TextInput",TextInput);
         UIObjectFactory.setPackageItemExtension("ui://Basic/TextArea",TextInput);
         UIObjectFactory.setPackageItemExtension("ui://Basic/NumericInput",NumericInput);
         UIObjectFactory.setPackageItemExtension("ui://Basic/ColorInput",ColorInput);
         UIObjectFactory.setPackageItemExtension("ui://Basic/ColorInputWithPreset",ColorInput);
         UIObjectFactory.setPackageItemExtension("ui://Basic/ResourceInput",ResourceInput);
         UIObjectFactory.setPackageItemExtension("ui://Basic/ListItemInput",ListItemInput);
         UIObjectFactory.setPackageItemExtension("ui://Basic/ListItemResourceInput",ListItemResourceInput);
         UIObjectFactory.setPackageItemExtension("ui://Basic/EditableTreeItem",EditableTreeItem);
         UIObjectFactory.setPackageItemExtension("ui://Basic/LinkButton",LinkButton);
         UIObjectFactory.setPackageItemExtension("ui://Builder/Timeline",TimelineComponent);
         UIObjectFactory.setPackageItemExtension("ui://Builder/GearPropsItem",GearPropsItem);
         UIObjectFactory.setPackageItemExtension("ui://Builder/ChildObjectInput",ChildObjectInput);
         UIObjectFactory.setPackageItemExtension("ui://Builder/ControllerEdit_PageItem",ControllerPageItem);
         UIObjectFactory.setPackageItemExtension("ui://Builder/ControllerEdit_ActionItem",ControllerActionItem);
         VersionCheck.inst.start();
         NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE,this.onInvoke);
         createOpenProjectWindow(null,false);
      }
      
      private function onInvoke(param1:InvokeEvent) : void
      {
         var _loc3_:OpenProjectWindow = null;
         var _loc4_:String = null;
         var _loc5_:File = null;
         if(param1.arguments.length > 0)
         {
            _loc4_ = param1.arguments[0];
            if(_loc4_.charAt(0) != "-")
            {
               if(param1.currentDirectory != null)
               {
                  _loc5_ = param1.currentDirectory.resolvePath(_loc4_);
                  if(_loc5_.exists)
                  {
                     FairyGUIEditor.createEditorWindow(_loc5_);
                     _loc3_ = findOpenProjectWindow();
                     if(_loc3_)
                     {
                        _loc3_.stage.nativeWindow.close();
                     }
                     return;
                  }
               }
            }
            else if(new NativeInvokeHandler().run(param1))
            {
               _loc3_ = findOpenProjectWindow();
               if(_loc3_)
               {
                  _loc3_.stage.nativeWindow.close();
               }
               return;
            }
         }
         if(os_mac)
         {
            return;
         }
         _loc3_ = findOpenProjectWindow();
         if(_loc3_)
         {
            _loc3_.stage.nativeWindow.activate();
         }
         else
         {
            createOpenProjectWindow(null,false);
         }
      }
   }
}
